package io.renren.modules.sys.controller;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;

import io.renren.modules.sys.service.SysConfigService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;



/**
 * 规划材料表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2019-01-21 16:44:32
 */
@RestController
@RequestMapping("/sys/file")
public class FileController extends AbstractController {

    @Autowired
    private SysConfigService sysConfigService;



    /**
     * 文件上传
     */
    @RequestMapping("/upload")
    public R upload(@RequestParam MultipartFile files[]) {
        String separator = File.separator;
        String path = sysConfigService.getValue("uploadfile");
        BufferedWriter bf = null;
        try {

            path = path + separator + getDeptId() + separator + "tian";

            path = saveFile(files, path);

            return R.ok().put("fileName", path.substring(path.lastIndexOf(separator) + 1)).put("success", true).put("msg", path);
        } catch (Exception e) {
            e.getMessage();

            return R.ok().put("msg", "").put("success", false);
        }
    }

    /**
     * 文件下载功能
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping("/fileDown")
    public void down(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileDir = request.getParameter("fileDir");
        //文件，fileName为需要下载的文件
        File file = new File(fileDir);

        if (file.exists()) {
            //获取输入流
            InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileDir)));
            //假如以中文名下载的话
            String filename = file.getName();
            //转码，免得文件名中文乱码
            filename = URLEncoder.encode(filename, "UTF-8");
            //设置文件下载头
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            int len = 0;
            while ((len = bis.read()) != -1) {
                out.write(len);
                out.flush();
            }
            out.close();
        }
    }


    /**
     * 预览pdf
     *
     * @param request
     * @param response
     * @param id
     * @throws Exception
     */
    @RequestMapping("/devDoc/{id}")
    public void devDoc(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/pdf");
        //读取文件(缓存字节流)
//        BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(null)));
        BufferedInputStream in =null;
        //写入相应的文件
        OutputStream out = response.getOutputStream();
        //读取数据
        //一次性取多少字节
        byte[] bytes = new byte[2048];
        //接受读取的内容(n就代表的相关数据，只不过是数字的形式)
        int n = -1;
        //循环取出数据
        while ((n = in.read(bytes, 0, bytes.length)) != -1) {
            //转换成字符串
            String str = new String(bytes, 0, n, "GBK");
            //写入相关文件
            out.write(bytes, 0, n);
        }
        //清楚缓存
        out.flush();
        //关闭流
        in.close();
        out.close();
    }
    /**
     * 预览pdf
     *
     * @param request
     * @param response
     * @param id
     * @throws Exception
     */
    @RequestMapping("/devDocpath")
    public void devDocpath(@RequestParam("path") String path, HttpServletRequest request, HttpServletResponse response, Integer id) throws Exception {
        //读取文件(缓存字节流)
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(path)));
        //写入相应的文件
        OutputStream out = response.getOutputStream();
        //读取数据
        //一次性取多少字节
        byte[] bytes = new byte[2048];
        //接受读取的内容(n就代表的相关数据，只不过是数字的形式)
        int n = -1;
        //循环取出数据
        while ((n = in.read(bytes, 0, bytes.length)) != -1) {
            //转换成字符串
            String str = new String(bytes, 0, n, "GBK");
            //写入相关文件
            out.write(bytes, 0, n);
        }
        //清楚缓存
        out.flush();
        //关闭流
        in.close();
        out.close();
    }



    public static int getPercent2(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        p2 = 530 / w * 100;
        p = Math.round(p2);
        return p;
    }


    @RequestMapping("/previewIMGpath")
    public  void  imgP(HttpServletRequest request, HttpServletResponse response) throws Exception {
   String path = request.getParameter("path");
        request.setCharacterEncoding("UTF-8");
        //读取文件(缓存字节流)
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(path)));
        //写入相应的文件
        OutputStream out = response.getOutputStream();
        //读取数据
        //一次性取多少字节
        byte[] bytes = new byte[2048];
        //接受读取的内容(n就代表的相关数据，只不过是数字的形式)
        int n = -1;
        //循环取出数据
        while ((n = in.read(bytes, 0, bytes.length)) != -1) {
            //转换成字符串
            String str = new String(bytes, 0, n, "GBK");
            //写入相关文件
            out.write(bytes, 0, n);
        }
        //清楚缓存
        out.flush();
        //关闭流
        in.close();
        out.close();

    }

    /**
     * 获取磁盘容量
     * @return
     */
    @RequestMapping("getDiskCapacity")
    public R getDiskCapacity(){
        Long totalSpace = 0l;
        Long freeSpace = 0l;
        try {
            String path = sysConfigService.getValue("uploadfile");
            if (path.length() > 0) {
                File file = new File(path.substring(0, 2));
                 totalSpace = (file.getTotalSpace()/1024/1024)-(10*1024);
                 freeSpace = (file.getFreeSpace()/1024/1024)-(10*1024);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("*****************为获取到磁盘容量*********************");
        }
        return R.ok().put("total",totalSpace).put("free",freeSpace);
    }


    public static String saveFile(MultipartFile[] files, String path) throws IOException {
        StringBuffer url = new StringBuffer();
        String separator = File.separator;
        // 判断文件是否为空
        if (files.length > 0) {
            try {
                File filepath = new File(path);
                if (!filepath.exists()) {
                    filepath.mkdirs();
                }
                // 文件保存路径

                for (MultipartFile file : files) {
                    String filename = file.getOriginalFilename();
                    String uil = path + separator + filename;
                    System.out.println(path);
                    System.out.println(separator);
                    System.out.println(filename);
                    file.transferTo(new File(path + separator + filename));

                    if (url.length() > 0) {
                        url.append(",");
                    }
                    url.append(uil);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return url + "";
    }

    /**
     * 文件删除
     *
     * @throws Exception
     */
    @RequestMapping("/fileDel")
    public void fileDel(@RequestParam("fileDir") String fileDir) throws Exception {
        File file = new File(fileDir);
        String fileName = file.getName();
        file.delete();

        //删除生成的预览文件
        String paths = sysConfigService.getValue("uploadfile");
        String separator = File.separator;
        Integer indexs = fileName.lastIndexOf(".");
        String suffix=fileName.substring(indexs).toLowerCase();
        String pdfPath = fileName.replace(suffix,"preview")+ ".pdf";
        pdfPath=paths+separator+separator+"preview"+separator+pdfPath;
        File files = new File(pdfPath);
        files.delete();
    }




}